<?php


class Order extends Api\Abstracte\Controller
{
    public $data = null;

    public function __construct()
    {
        parent::__construct();
        $this->load->model('common_model');
        $this->load->model('mysql_model');
        $this->load->model('data_model');
        $this->common_model=$this->common_model;
        $this->mysql_model = $this->mysql_model;
        $this->data_model = $this->data_model;
        $this->data ='{
            "id":-1,
            "buId":0,
            "contactName":"(空)",
            "date":"2020-12-13",
            "billNo":"'.str_no('CBTZ').'",
            "transTypeId":"",
            "transTypeName":"",
            "entries":[
                {
                    "invId":"17",
                    "invNumber":"GH1337t47",
                    "invName":"商品名称很长",
                    "invSpec":"红色 xxl 冬装",
                    "skuId":-1,
                    "skuName":"",
                    "unitId":"0",
                    "mainUnit":"123/g",
                    "qty":"1.00",
                    "price":"0.00",
                    "amount":"0.00",
                    "description":"",
                    "locationId":"7",
                    "locationName":"北京仓库"
                }
            ],
            "totalQty":"1.00",
            "totalAmount":"0.00",
            "description":""
        }';
    }

    public function add(){
        $json = $this->input->post('postData',TRUE);
        $ar = json_decode($json,true);
        $ids = $ar['entries'];
        $r = $this->getData($ids);
        $ar['billNo'] = str_no('CBTZ');
        $ar['entries'] = json_encode($r);
        //$data = $this->data;
        $data = json_encode($ar);
        exit($data);
        $this->addOo($data);
    }

    private function getData($ids=0){
        $result =$this->db->query("select id as invId,name as invName,number as invNumber,spec as invSpec,unitName as mainUnit,amount,remark as description,locationId,locationName from ci_goods where id in (1,2,3)")->result();
        $data = [];
        if(count($result)<0) str_alert(-1,'提交的是空数据');;
        foreach($result as $k=>$v){
            $data[$k]['invId'] = $v->invId;
            $data[$k]['invNumber'] = $v->invNumber;
            $data[$k]['invName'] = $v->invName;
            $data[$k]['invSpec'] = $v->invSpec;
            $data[$k]['skuId'] = -1;
            $data[$k]['skuName'] = "";
            $data[$k]['unitId'] = 0;
            $data[$k]['qty'] = 1;
            $data[$k]['price'] = "0.00";
            $data[$k]['amount'] = "0.00";
            $data[$k]['description'] = $v->description;
            $data[$k]['locationId'] = $v->locationId;
            $data[$k]['locationName'] = $v->locationName;
        }
        return $data;
    }


    public function addOo($data){

        if (strlen($data)>0) {
            $data = $this->Oo_validform((array)json_decode($data, true));
            $info = elements(array(
                'billNo','billType','transType','transTypeName','buId','createTime',
                'billDate','description','totalQty','totalAmount','outLocationId',
                'uid','userName','modifyTime','postData'),$data);
            $this->db->trans_begin();
            $iid = $this->mysql_model->insert('invoice',$info);
            $this->Oo_invoice_info($iid,$data);
            if ($this->db->trans_status() === FALSE) {
                $this->db->trans_rollback();
                str_alert(-1,'SQL错误回滚');
            } else {
                $this->db->trans_commit();
                // $this->common_model->logs('新增其他出库 单据编号：'.$data['billNo']);
                $this->get_updateOut($iid);
            }
        }
        str_alert(-1,'提交的是空数据');
    }
    private function get_updateOut($id) {
        $data = $this->data_model->get_invoice('a.isDelete=0 and a.id='.$id.' and a.billType="OO"',1);
        if (count($data)>0) {
            $list = $this->data_model->get_invoice_info('a.isDelete=0 and a.iid='.$id.'  order by a.id desc');
            foreach ($list as $arr=>$row) {
                $v[$arr]['invSpec']      = $row['invSpec'];
                $v[$arr]['goods']        = $row['invNumber'].' '.$row['invName'].' '.$row['invSpec'];
                $v[$arr]['invName']      = $row['invName'];
                $v[$arr]['qty']          = (float)abs($row['qty']);
                $v[$arr]['amount']       = (float)abs($row['amount']);
                $v[$arr]['price']        = (float)$row['price'];
                $v[$arr]['mainUnit']     = $row['mainUnit'];
                $v[$arr]['description']  = $row['description'];
                $v[$arr]['invId']        = intval($row['invId']);
                $v[$arr]['invNumber']    = $row['invNumber'];
                $v[$arr]['locationId']   = intval($row['locationId']);
                $v[$arr]['locationName'] = $row['locationName'];
                $v[$arr]['unitId']       = intval($row['unitId']);
                $v[$arr]['skuId']        = intval($row['skuId']);
                $v[$arr]['skuName']      = '';
            }
            $json['status']              = 200;
            $json['msg']                 = 'success';
            $json['data']['id']          = intval($data['id']);
            $json['data']['buId']        = intval($data['buId']);
            $json['data']['contactName'] = $data['contactName'];
            $json['data']['date']        = $data['billDate'];
            $json['data']['billNo']      = $data['billNo'];
            $json['data']['billType']    = $data['billType'];
            $json['data']['modifyTime']  = $data['modifyTime'];
            $json['data']['createTime']  = $data['createTime'];
            $json['data']['transType']   = intval($data['transType']);
            $json['data']['totalQty']    = (float)$data['totalQty'];
            $json['data']['totalAmount'] = (float)abs($data['totalAmount']);
            $json['data']['userName']    = $data['userName'];
            $json['data']['description'] = $data['description'];
            $json['data']['amount']      = (float)abs($data['totalAmount']);
            $json['data']['checked']     = intval($data['checked']);
            $json['data']['status']      = intval($data['checked'])==1 ? 'view' : 'edit';
            $json['data']['entries']     = isset($v) ? $v : array();
            die(json_encode($json));
        }
        str_alert(-1,'单据不存在');
    }

    private function Oo_validform($data) {
        $data['id']              = isset($data['id']) ? intval($data['id']) : 0;
        $data['buId']            = intval($data['buId']);
        $data['transType']       = intval($data['transTypeId']);
        $data['totalQty']        = (float)$data['totalQty'];
        $data['billType']        = 'OO';
        $data['billDate']        = $data['date'];
        $data['transTypeName']   = $data['transTypeName'];
        $data['uid']             = 1;
        $data['userName']        = '米辰科技';
        $data['modifyTime']      = date('Y-m-d H:i:s');
        $data['createTime']      = $data['modifyTime'];
        $data['accounts']        = isset($data['accounts']) ? $data['accounts'] : array();
        $data['entries']         = isset($data['entries']) ? $data['entries'] : array();

        count($data['entries']) < 1 && str_alert(-1,'提交的是空数据');


        if ($data['id']>0) {
            $invoice = $this->mysql_model->get_rows('invoice',array('id'=>$data['id'],'billType'=>'OO','isDelete'=>0));
            count($invoice)<1 && str_alert(-1,'单据不存在、或者已删除');
            $data['checked'] = $invoice['checked'];
            $data['billNo'] = $invoice['billNo'];
        } else {
            $data['billNo'] = str_no('QTCK');
        }


        $system    = $this->common_model->get_option('system');
        if ($system['requiredCheckStore']==1) {
            $inventory = $this->data_model->get_invoice_info_inventory();
        }
        $storage   = array_column($this->mysql_model->get_results('storage','(disable=0)'),'id');
        foreach ($data['entries'] as $arr=>$row) {
            intval($row['invId']) < 1 && str_alert(-1,'请选择商品');
            (float)$row['qty'] < 0  && str_alert(-1,'商品数量要为数字，请输入有效数字！');
            (float)$row['price'] < 0  && str_alert(-1,'商品销售单价要为数字，请输入有效数字！');
            intval($row['locationId']) < 1 && str_alert(-1,'请选择相应的仓库！');
            !in_array($row['locationId'],$storage) && str_alert(-1,$row['locationName'].'不存在或不可用！');


            if ($system['requiredCheckStore']==1 && $data['id']<1) {
                if (intval($data['transType'])==150806) {
                    if (isset($inventory[$row['invId']][$row['locationId']])) {
                        $inventory[$row['invId']][$row['locationId']] < (float)$row['qty'] && str_alert(-1,$row['locationName'].$row['invName'].'商品库存不足！');
                    } else {
                        str_alert(-1,$row['invName'].'库存不足！');
                    }
                }
            }
            if ($data['transType']==150706) {
                $inLocationId[]  = $row['locationId'];
            } else {
                $outLocationId[] = $row['locationId'];
            }
        }
        if ($data['transType']==150706) {
            $data['inLocationId']  = join(',',array_unique($inLocationId));
        } else {
            $data['outLocationId'] = join(',',array_unique($outLocationId));
        }
        $data['postData'] = serialize($data);
        return $data;
    }

    private function Oo_invoice_info($iid,$data) {
        $amount = 0;
        $profit = $this->data_model->get_profit('and billDate<="'.date('Y-m-d').'"');
        foreach ($data['entries'] as $arr=>$row) {
            $price = isset($profit['inprice'][$row['invId']][$row['locationId']]) ? $profit['inprice'][$row['invId']][$row['locationId']] : 0;
            $amount   += -abs($row['qty']) * $price;
            $v[$arr]['iid']           = $iid;
            $v[$arr]['billNo']        = $data['billNo'];
            $v[$arr]['buId']          = $data['buId'];
            $v[$arr]['transType']     = $data['transType'];
            $v[$arr]['transTypeName'] = $data['transTypeName'];
            $v[$arr]['billDate']      = $data['billDate'];
            $v[$arr]['billType']      = $data['billType'];
            $v[$arr]['invId']         = intval($row['invId']);
            $v[$arr]['skuId']         = intval($row['skuId']);
            $v[$arr]['unitId']        = intval($row['unitId']);
            $v[$arr]['locationId']    = intval($row['locationId']);
            $v[$arr]['qty']           = -abs($row['qty']);
            $v[$arr]['amount']        = -abs($row['qty']) * $price;
            $v[$arr]['price']         = $price;
            $v[$arr]['description']   = $row['description'];
        }
        if (isset($v)) {
            if ($data['id']>0) {
                $this->mysql_model->delete('invoice_info',array('iid'=>$iid));
            }
            $this->mysql_model->insert('invoice_info',$v);
            $this->mysql_model->update('invoice',array('totalAmount'=>$amount),array('id'=>$iid));
        }
    }

}